﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web_Oto.Business;
using Web_Oto.Common;

namespace Web_Oto
{
    public partial class Products : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GetProducts(); 
            }
        }

        private void GetSeoInformations(int? categoryId, int? parentId)
        {            
            if (categoryId == null && parentId == null)
            {
                var seoBus = new SeoBus();
                var seo = seoBus.GetSeoPage("product");
                if (seo != null)
                {
                    Page.Title = seo.Title;
                    Page.MetaKeywords = seo.Keyword;
                    Page.MetaDescription = seo.Description;                    
                }
            }
            else if (categoryId == null && parentId != null)
            {
                var categoryBus = new CategoryBus();
                var category = categoryBus.GetCategoryById(parentId ?? 0);
                if (category != null)
                {
                    Page.Title = category.SEO_Title;
                    Page.MetaKeywords = category.SEO_Keyword;
                    Page.MetaDescription = category.SEO_Description;
                }
            }
            else if (categoryId != null && parentId != null)
            {
                var categoryBus = new CategoryBus();
                var category = categoryBus.GetCategoryById(categoryId ?? 0);
                if (category != null)
                {
                    Page.Title = category.SEO_Title;
                    Page.MetaKeywords = category.SEO_Keyword;
                    Page.MetaDescription = category.SEO_Description;
                }
            }
        }

        private void GetProducts()
        {
            var productBus = new ProductBus();

            var categoryName = (Page.RouteData.Values.Count > 0 && Page.RouteData.Values.ContainsKey("category")) ?
                CommonHelper.NiceUrl(Page.RouteData.GetRequiredString("category")) : null;

            var subCategoryName = (Page.RouteData.Values.Count > 0 && Page.RouteData.Values.ContainsKey("sub_category")) ?
                CommonHelper.NiceUrl(Page.RouteData.GetRequiredString("sub_category")) : null;

            var parentId = productBus.GetCategoryByName(categoryName);
            var categoryId = productBus.GetCategoryByName(subCategoryName);

            var currentpage = (Page.RouteData.Values.Count > 0 && Page.RouteData.Values.ContainsKey("currentpage"))
                                   ? Convert.ToInt32(Page.RouteData.GetRequiredString("currentpage"))
                                   : 1;
            var totalRecord = 0;
            var itemPerPage = Convert.ToInt32(ConfigurationManager.AppSettings["itemperpage"]);
            var products = productBus.GetProducts(categoryId, parentId, currentpage,itemPerPage,out totalRecord);
            if (products.Any())
                Breakcrum(products.FirstOrDefault().CategoryName, categoryName);
            if(totalRecord > itemPerPage)
                PagingProducts(categoryName, subCategoryName, itemPerPage,currentpage,totalRecord);
            var sb = new StringBuilder();
            var key_descript = "";
            var path = ConfigurationManager.AppSettings["productPath"];
            foreach (var product in products)
            {
                sb.AppendFormat("<li><a href='/san-pham/{0}/{1}/{2}-{3}.html' class='mask_home'><div></div><img src='{4}/{5}' title='{6}' alt='{6}'></a>",
                    CommonHelper.NiceUrl(product.CategoryParentName.ToLower()), CommonHelper.NiceUrl(product.CategoryName.ToLower()),
                    CommonHelper.NiceUrl(product.Name.ToLower()), product.Id, path, product.Image, product.TitleOfImage);
                sb.AppendFormat("<div><h5><a href='/san-pham/{0}/{1}/{2}-{3}.html' class='product-name'>{4}</a></h5></div>", CommonHelper.NiceUrl(product.CategoryParentName.ToLower()), CommonHelper.NiceUrl(product.CategoryName.ToLower()),
                    CommonHelper.NiceUrl(product.Name.ToLower()), product.Id, product.Name);
                sb.Append("</li>");
                //key_descript += CommonHelper.NiceUrl(product.Name) + ", " + product.Name + ",";
            }
            GetSeoInformations(categoryId, parentId);
            ltrProductsList.Text = sb.ToString();
        }

        private void Breakcrum(string subCategory = null, string category = null)
        {
            var sb = new StringBuilder();
            var breakLine = "<img src='/images/next-icon.png' alt='' />";
            if (!String.IsNullOrWhiteSpace(category) && !String.IsNullOrWhiteSpace(subCategory))
            {
                sb.Append("<a href='/san-pham.html'>Sản phẩm</a>");
                if (!String.IsNullOrWhiteSpace(subCategory))
                {
                    sb.Append(breakLine);
                    sb.AppendFormat("<span>{0}</span>", subCategory.ToLower());
                }
            }
            else
                sb.Append("<span>Sản phẩm</span>");
            
            ltrBreakCrum.Text = sb.ToString();
        }

        private void PagingProducts(string category, string subCategory, int itemPerPage, int currentPage, int? totalRecord)
        {
            var sb = new StringBuilder();
            int totalPage = (Convert.ToInt32(totalRecord / itemPerPage) == 0) ? 1 :
                Convert.ToInt32(totalRecord / itemPerPage) + 1;
            var currentUrl = Page.Request.Url.AbsolutePath.Split(new char[] { '/' })[1].Replace(".html","");
            if(!string.IsNullOrEmpty(category) && !string.IsNullOrEmpty(subCategory))
            {
                
            }
            int firstPage = 1;
            int lastPage = 1;
            int maxPage = Convert.ToInt32(ConfigurationManager.AppSettings["MaxPage"]);
            firstPage = (currentPage < maxPage) ? (currentPage / maxPage) * maxPage + 1 : (maxPage / currentPage) * maxPage;
            lastPage = (currentPage / maxPage > 0) ? (currentPage / maxPage) * maxPage + maxPage : maxPage;
            if (lastPage > totalPage)
                lastPage = totalPage;
            if (Page.Request.Url.AbsolutePath.Split(new char[] { '/' }).Length <= 3)
            {
                sb.AppendFormat(currentPage == 1 ? "<li>Đầu</li>" : "<li><a href='/{0}/1.html'>Đầu</a></li>", currentUrl);
                for (int page = firstPage; page <= lastPage; page++)
                {
                    sb.AppendFormat(
                        page == currentPage ? "<li class='currentpage'>{0}</li>" : "<li><a href='/{1}/{0}.html'>{0}</a></li>",
                        page, currentUrl);
                }
                sb.AppendFormat(currentPage == totalPage ? "<li>Cuối</li>" : "<li><a href='/{0}/{1}.html'>Cuối</a></li>",
                                currentUrl, totalPage);
            }
            else
            {
                var fullpath = Page.Request.Url.AbsolutePath.Split(new char[] {'/'});
                var categoryName = fullpath[2];
                var subCategoryName = fullpath[3];
                sb.AppendFormat(currentPage == 1 ? "<li>Đầu</li>" : "<li><a href='/{0}/{1}/{2}/1.html'>Đầu</a></li>", 
                    currentUrl,categoryName, subCategoryName);
                for (int page = firstPage; page <= lastPage; page++)
                {
                    sb.AppendFormat(
                        page == currentPage ? "<li class='currentpage'>{0}</li>" : "<li><a href='/{1}/{2}/{3}/{0}.html'>{0}</a></li>",
                        page, currentUrl, categoryName, subCategoryName);
                }
                sb.AppendFormat(currentPage == totalPage ? "<li>Cuối</li>" : "<li><a href='/{0}/{1}/{2}/{3}.html'>Cuối</a></li>",
                                currentUrl, categoryName, subCategoryName, totalPage);
            }
            ltrPaging.Text = sb.ToString();
        }
    }
}